package nd.privatebrowser;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.ConnectException;
import java.net.MalformedURLException;
import java.net.URL;

import android.app.AlertDialog;
import android.os.AsyncTask;
import android.widget.Toast;

public class PageLoaderTask extends AsyncTask<Void, Void, byte[]> {
	
	private String inputUrl;
	private String errorString="";
	private Exception ex;
	private URL validUrl;
	private boolean isBack = false;
	private Boolean connectionCheck = null;
	
	private PrivateBrowserActivity browserActivity;
	
	public PageLoaderTask(PrivateBrowserActivity browserActivity, String url){
		this.inputUrl = url;
		this.browserActivity = browserActivity;
	}
	
    public boolean isBack() {
		return isBack;
	}

	public void setBack(boolean isBack) {
		this.isBack = isBack;
	}

	@Override
	protected void onPreExecute() {		
//    	Toast.makeText(browserActivity, "loading..", Toast.LENGTH_SHORT).show();
		
	}
		

	@Override
	protected void onProgressUpdate(Void... values) {
		Toast.makeText(browserActivity, "loading..", Toast.LENGTH_SHORT).show();
	}

	protected byte[] doInBackground(Void... params) {
		byte[] b=null;
		try {
    		
    		if(browserActivity.getBrowser().getRenderedUrl() != null) {        			        		
    			validUrl = new URL(new URL(browserActivity.getBrowser().getRenderedUrl()), inputUrl);
    		} else {
    			validUrl = new URL(inputUrl);
    		}
    		
    		publishProgress();
    	
    		b = BrowserUtil.loadUrl(validUrl);
    		
		} catch ( MalformedURLException e) {
			ex = e;
		} catch (Exception e) {
			ex = e;
			connectionCheck = BrowserUtil.checkTorConnection();			
		}
		
        return b;
    }
    
    
    protected void onPostExecute(byte[] b) {
    	try {
    	if(ex != null) {

    		try {
				throw ex;	
    		} catch (MalformedURLException e) {
    			showMessage("Malformed URL: "+e.getMessage());
    			return;
			} catch (ConnectException e) {
				if(e.getMessage().contains(BrowserUtil.TOR_HTTP_PROXY_HOST+":"+BrowserUtil.TOR_HTTP_PROXY_PORT)) {
					browserActivity.askToStartTor();
					return;
				}
			} catch(FileNotFoundException e) {				
			} catch (Exception e) {				
			}
			
			if(connectionCheck != null && connectionCheck.equals(Boolean.FALSE)) {
				browserActivity.askToStartTor();
				return;
			} 
			showMessage(""+ex);
			
    		return;
    	}
    	
    	try {
        		        		        		        	
        	String renderedText =  BrowserUtil.renderText(b);
			
			browserActivity.getBrowser().setCurrentPage(renderedText, validUrl.toString(), isBack());
        	
			browserActivity.updateUrlField();
        									
			Toast.makeText(browserActivity, "Done", Toast.LENGTH_SHORT).show();
			
    	} catch (IOException e1) {
    		showMessage(""+e1);
		}
    	
    	} finally {
    		browserActivity.updateGoButtonText(true);
    	}
    }
    
    

	@Override
	protected void onCancelled() {
		Toast.makeText(browserActivity, "Stopped", Toast.LENGTH_SHORT).show();
	}

	private void showMessage(String additionalMessage) {
		AlertDialog.Builder dialog = new AlertDialog.Builder(browserActivity);
		dialog.setTitle("Error");
		dialog.setMessage(errorString+"\n"+additionalMessage);
		dialog.show();
	}
	
}